aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/invoice/[id]/+layout.server.ts
blob: e2f03fd7f8db350b95fbc1244d445ec7d2b32306 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import * as Qr from "qrcode-base64";
import { get } from "$lib/utils";
import { redirect } from "@sveltejs/kit";

export async function load({ depends, params, url, parent }) {
  depends("app:invoice");

  let { subject, user } = await parent();
  let { id } = params;
  let invoice;

  if (id) {
    invoice = await get(`/invoice/${id}`);
    let options = !!url.searchParams.get("options");

    if (
      user &&
      invoice.uid !== user.id &&
      !(url.pathname.includes("tip") || url.pathname.includes("memo")) &&
      !options
    ) {
      redirect(307, `/send/invoice/${id}`);
    }

    let { amount, pending, received } = invoice;
    amount = parseInt(amount);
    subject = user || invoice.user;

    let paid =
      (!amount && (pending || received)) ||
      (amount > 0 && (pending >= amount || received >= amount));
    if (paid && !url.pathname.endsWith("paid")) {
      redirect(307, `/invoice/${id}/paid` + (options ? "?options=true" : ""));
    }
  }

  let src = Qr.drawImg(invoice?.text || "", { size: 500 });
  return { id, invoice, subject, src, user };
}